package com.qiyuesuo.controller;

import com.qiyuesuo.api.CommonResult;
import com.qiyuesuo.domain.MyFile;
import com.qiyuesuo.service.FileService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 王帅涛
 * @date 2021/5/28 19:36
 */
@RestController
@RequestMapping("/api/file")

public class FileController {
    @Resource
    private FileService fileService;
    //文件上传接口
    @PostMapping
    public CommonResult<String> uploadFile(@RequestParam("file") MultipartFile file){
        try {
            String uuid = fileService.uploadFile(file);
            return CommonResult.success(uuid);
        }catch (Exception e){
            return CommonResult.failed("上传失败");
        }
    }

    //文件下载接口
    @GetMapping("/download")
    public String downloadFile(@RequestParam("fileId") String fileId,
                                    HttpServletResponse response){
        try {
            fileService.downloadFile(fileId,response);
        } catch (Exception e) {
            e.printStackTrace();
            return "410";
        }
        return "";
    }
    //获取文件元数据接口
    @GetMapping("/meta")
    public CommonResult<MyFile> metaFile(@RequestParam("fileId") String fileId){
        MyFile myFile = fileService.getById(fileId);
        return CommonResult.success(myFile);
    }
}
